package com.mdhw.config;

import com.mdhw.common.enums.MessageEnum;
import com.mdhw.common.exception.BusException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());

        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(BusException.class)
    @ResponseBody
    public R<String> handle(BusException e) {
        if (e instanceof BusException) {
            BusException exception = (BusException) e;
            Exception errorE = exception.getException() == null ? exception : exception.getException();
            return R.error(exception.getMessageEnum().code, e.getMessage());
        } else {
            log.error(e.getMessage(), e);
            return R.error(MessageEnum.ERROR.getCode(), MessageEnum.ERROR.getMessage(), e.getMessage());
        }
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R<String> handle(BindException e) {
        if (e instanceof BindException) {
            BindException exception = (BindException) e;
            return R.error(MessageEnum.VALIDATE_ERROR.getCode(), exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        } else {
            log.error(e.getMessage(), e);
            return R.error(MessageEnum.ERROR.getCode(), MessageEnum.ERROR.getMessage(), e.getMessage());
        }
    }

}
